#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import time

import io
import network
import settings
import switch
import pyrcswitch

class HomeSwitch:
	def __init__(self):
		self.init_settings()
		
		pyrcswitch.init(self.settings["pin"])
		
		self.rooms = {}
		for i,label in self.settings["rooms"].items():
			self.rooms[int(i)] = label
		
		self.switches = {}
		for i,data in self.settings["switches"].items():
			self.switches[int(i)] = switch.Switch(self, data["room"], data["label"], data["system_code"], data["unit_code"])
		
		self.network = network.NetworkServer(self, self.settings["discover_port"])
	
	def init_settings(self):
		self.settings = settings.Settings()
		
		if not "pin" in self.settings:
			self.settings["pin"] = 0
		if not "discover_port" in self.settings:
			self.settings["discover_port"] = 54038
		if not "rooms" in self.settings:
			self.settings["rooms"] = {}
		if not "switches" in self.settings:
			self.settings["switches"] = {}
	
	def save(self):
		rooms = {}
		for i, label in self.rooms.items():
			rooms[str(i)] = label
		self.settings["rooms"] = rooms
		
		switches = {}
		for i, switch in self.switches.items():
			switches[str(i)] = \
			{
				"room": switch.room,
				"label": switch.label,
				"system_code": switch.system_code,
				"unit_code": switch.unit
			}
		self.settings["switches"] = switches
	
	def on_change(self, switch):
		pass
	
	def on_connection_create(self, socket):
		print "Connection established: ", socket
	
	def on_connection_destroy(self, socket):
		print "Connection closed:      ", socket
	

def main():
	homeswitch = HomeSwitch()
	try:
		io.get_default_io().run()
	except (KeyboardInterrupt, SystemExit):
		print '\nReceived keyboard interrupt.'

if __name__ == "__main__":
	main()

